﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using StellarMedical.ServiceReference;
using System.Windows.Media.Imaging;
using System.IO;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Data;

namespace StellarMedical
{
    public partial class ImageFader : UserControl, INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;

        //private ObservableCollection<String> ImagePaths;

        private System.Windows.Threading.DispatcherTimer timer { get; set; }

        private int currentImageIndex
        {
            get
            {
                return (int)GetValue(CurrentImageIndexProperty);
            }

            set
            {
                SetValue(CurrentImageIndexProperty, value);

                if(PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("currentImageIndex"));
            }
        }
        

        private ObservableCollection<Image> images { get; set; }
        
        // test code
        private bool imagesLoaded { get; set; }

        // test code
        private MedicalServiceClient serviceRef; 

        public static DependencyProperty CurrentImageIndexProperty  = DependencyProperty.Register(
            "currentImageIndex", typeof(int), typeof(ImageFader), new PropertyMetadata(0, OnCurrentImageIndexPropertyChanged));

        private static void OnCurrentImageIndexPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            (d as ImageFader).FadeOut.Begin();
        }

        public ImageFader()
        {
            InitializeComponent();

            //test code
            // connect the service
            //try
            //{
            //    serviceRef = ServiceConfig.Connect();
            //    serviceRef.getImageFaderPathsCompleted += new EventHandler<getImageFaderPathsCompletedEventArgs>(serviceRef_getImageFaderPathsCompleted);
            //}
            //catch (Exception ex)
            //{
            //    MessageTb.Text = ex.Message;
            //}

            
        }

        //test code
        void serviceRef_getImageFaderPathsCompleted(object sender, getImageFaderPathsCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageTb.Text = e.Error.Message;
                return;
            }
            else
            {
                //ImagePaths = e.Result;
                //MessageTb.Text = "done";
            }

            //if (ImagePaths.Count == 0)
            //{
            //    MessageTb.Text = "No Images found";
            //    return;
            //}

            // load all the images






        }

        void timer_Tick(object sender, EventArgs e)
        {
            if ((currentImageIndex + 1) == images.Count)
            {
                currentImageIndex = 0;
            }
            else
            {
                currentImageIndex++;
            }
        }



        void FadeOut_Completed(object sender, EventArgs e)
        {
            backgroundImageBrush.ImageSource = images[this.currentImageIndex].Source;
            FadeIn.Begin();
        }

        void btn_Click(object sender, RoutedEventArgs e)
        {
            // we need to reset to timer
            timer.Start();

            this.currentImageIndex = (int)(sender as Button).Tag;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

            




            //serviceRef.getImageFaderPathsAsync();

            //return;

            //(this.Resources["Image2.JPG"] as BitmapImage)


            // setup a static array of image paths

            ButtonContainer.Children.Clear();

            ObservableCollection<BitmapImage> ImagePaths = new ObservableCollection<BitmapImage>();

            ImagePaths.Add(this.Resources["Image2"] as BitmapImage);
            ImagePaths.Add(this.Resources["Image3"] as BitmapImage);
            ImagePaths.Add(this.Resources["Image4"] as BitmapImage);
            ImagePaths.Add(this.Resources["Image5"] as BitmapImage);
            ImagePaths.Add(this.Resources["Image6"] as BitmapImage);
            ImagePaths.Add(this.Resources["Image7"] as BitmapImage);

            (this.Resources["Image7"] as BitmapImage).ImageOpened += new EventHandler<RoutedEventArgs>(ImageFader_ImageOpened);

            int i = 0;

            images = new ObservableCollection<Image>();

            //WebClient wc;

            StackPanel sp = new StackPanel()
            {
                Height = 1,
                Width = 1
            };

            foreach (BitmapImage p in ImagePaths)
            {
                i++;

                Image img = new Image();
                img.Stretch = Stretch.UniformToFill;


                img.Source = p;

                images.Add(img);

                sp.Children.Add(img);

                //wc = new WebClient();
                //wc.OpenReadCompleted += new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
                //wc.OpenReadAsync(p.UriSource, UriKind.RelativeOrAbsolute);

                // create a button for this image
                Button btn = new Button()
                {
                    Margin = new Thickness(3),
                    Content = i.ToString(),
                    Tag = i - 1,
                    Style = App.Current.Resources["ImageFaderButtonStyle"] as Style
                };

                Binding selectedBinding = new Binding("currentImageIndex");
                selectedBinding.Source = this;

                selectedBinding.Mode = BindingMode.OneWay;
                selectedBinding.ConverterParameter = i - 1;
                selectedBinding.Converter = new Converters.FaderButtonBackgroundConverter();

                btn.SetBinding(Button.BorderThicknessProperty, selectedBinding);

                btn.Click += new RoutedEventHandler(btn_Click);
                ButtonContainer.Children.Add(btn);

            }


            //MessageBox.Show("v3");
            this.LayoutRoot.Children.Add(sp);

            //MessageBox.Show("test");

            backgroundImageBrush.ImageSource = images[0].Source;

            //imagesLoaded = true;

            this.currentImageIndex = 0;

            FadeOut.Completed += new EventHandler(FadeOut_Completed);

            try
            {
                timer.Stop();
            }
            catch (Exception) { }

            timer = new System.Windows.Threading.DispatcherTimer();

            // setup the change image timer
            timer.Interval = TimeSpan.FromSeconds(10);
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
            //MessageTb.Text = "";

        }

        void ImageFader_ImageOpened(object sender, RoutedEventArgs e)
        {
            MessageTb.Text = "";
        }

        void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            
        }


    }
}
